/*
*Copyright (c) Nikhil Jain.
*Project ICARUS, communications and 
*artificial intelligence.
*/



/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
 */
package javadrone.server;

//~--- non-JDK imports --------------------------------------------------------

import javadrone.RemoteImage;

import javadrone.server.listeners.VideoStateChangeListener;

import javadrone.statedata.VideoCaptureStateData;

//~--- JDK imports ------------------------------------------------------------

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import java.util.Iterator;
import java.util.concurrent.ArrayBlockingQueue;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

/**
 *
 * @author Nikzzay
 */
public class ImageConsumer extends ArrayBlockingQueue<BufferedImage> implements VideoStateChangeListener {
    public ImageConsumer(int qCapacity) {
        super(qCapacity);
    }

    @Override
    public void stateChanged(StateChangeEvent<VideoCaptureStateData> sce) {
        try {
            RemoteImage ri = ((VideoCaptureStateData.VideoCaptureState) sce.getCurrentState().getData()).getImage();

            System.out.println("Image received with delay: " + (System.currentTimeMillis() - ri.getTimestamp())
                               + " milliseconds");

            ByteArrayInputStream bis     = new ByteArrayInputStream(ri.getBytes());
            Iterator<?>          readers = ImageIO.getImageReadersByFormatName("jpg");
            ImageReader          reader  = (ImageReader) readers.next();
            Object               source  = bis;
            ImageInputStream     iis     = ImageIO.createImageInputStream(source);

            reader.setInput(iis, true);

            ImageReadParam param = reader.getDefaultReadParam();
            Image          image = reader.read(0, param);
            BufferedImage  bi    = new BufferedImage(image.getWidth(null), image.getHeight(null),
                                   BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = bi.createGraphics();

            g2.drawImage(image, null, null);

            if (this.remainingCapacity() <= 0) {
                remove();
            }

            add(bi);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}


//~ Formatted by Jindent --- http://www.jindent.com
